import http.client
from bs4 import BeautifulSoup
import os
import json
import requests

conn = http.client.HTTPSConnection("www.replacebase.co.uk")
payload = ''
headers = {
    'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
    'Accept': '*/*',
    'Host': 'www.replacebase.co.uk',
    'Connection': 'keep-alive'
}
conn.request("GET", "/itrucolor-iphone-xr-screen-vivid-colour", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

if res.getcode() == 200:
    # 使用BeautifulSoup解析HTML
    soup = BeautifulSoup(data.decode("utf-8"), 'html.parser')

    # 查找所有的script标签
    scripts = soup.find_all('script')

    # 遍历script标签，查找包含data-gallery-role="gallery-placeholder"的数据
    for script in scripts:
        if "data-gallery-role=gallery-placeholder" in str(script):
            # 获取JSON格式的数据
            try:
                data_body = json.loads(script.text.strip())["[data-gallery-role=gallery-placeholder]"]
                if "mage/gallery/gallery" in data_body:
                    images = data_body["mage/gallery/gallery"]["data"]
                    for index, img in enumerate(images):
                        image_url = img["full"]
                        img_name = 'sss_' + str(index)
                        print(f'images:{img["full"]}')
                        if '.webp' in img["full"]:
                            img_name = img_name + '.webp'
                        else:
                            img_name = img_name + '.jpg'
                        img_data = requests.get(image_url, headers=headers).content
                        with open(f'./result/images/{img_name}', 'wb') as handler:
                            handler.write(img_data)
            except json.JSONDecodeError as e:
                print(f"Error decoding JSON: {e}")
